import React, { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { Statistics, Order } from '../types';
import { apiService } from '../services/api';
import { useRealtime } from '../hooks/useRealtime';

const Dashboard: React.FC = () => {
  const [statistics, setStatistics] = useState<Statistics | null>(null);
  const [recentOrders, setRecentOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const { onStatisticsUpdate, onOrderUpdate } = useRealtime();

  // 加载数据
  const loadData = useCallback(async () => {
    try {
      setLoading(true);
      const [statsData, ordersData] = await Promise.all([
        apiService.getStatistics(),
        apiService.getOrders({ limit: 10, sortBy: 'createdAt', sortOrder: 'desc' }),
      ]);
      setStatistics(statsData);
      setRecentOrders(ordersData.items);
      setError('');
    } catch (err: any) {
      setError(err.message || '加载数据失败');
    } finally {
      setLoading(false);
    }
  }, []);

  // 实时更新统计数据
  const handleStatisticsUpdate = useCallback((newStats: Statistics) => {
    setStatistics(newStats);
  }, []);

  // 实时更新工单数据
  const handleOrderUpdate = useCallback((updatedOrder: Order) => {
    setRecentOrders(prevOrders => {
      const existingIndex = prevOrders.findIndex(order => order._id === updatedOrder._id);
      if (existingIndex >= 0) {
        // 更新现有工单
        const newOrders = [...prevOrders];
        newOrders[existingIndex] = updatedOrder;
        return newOrders;
      } else {
        // 添加新工单到顶部
        return [updatedOrder, ...prevOrders.slice(0, 9)];
      }
    });
    // 刷新统计数据
    loadData();
  }, [loadData]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  useEffect(() => {
    onStatisticsUpdate(handleStatisticsUpdate);
    onOrderUpdate(handleOrderUpdate);
  }, [onStatisticsUpdate, onOrderUpdate, handleStatisticsUpdate, handleOrderUpdate]);

  const getStatusColor = (status: Order['status']) => {
    const colors = {
      pending: 'bg-yellow-100 text-yellow-800 border-yellow-200',
      assigned: 'bg-blue-100 text-blue-800 border-blue-200',
      processing: 'bg-indigo-100 text-indigo-800 border-indigo-200',
      completed: 'bg-green-100 text-green-800 border-green-200',
      cancelled: 'bg-red-100 text-red-800 border-red-200',
    };
    return colors[status] || colors.pending;
  };

  const getStatusText = (status: Order['status']) => {
    const texts = {
      pending: '待处理',
      assigned: '已分配',
      processing: '处理中',
      completed: '已完成',
      cancelled: '已取消',
    };
    return texts[status] || status;
  };

  const getUrgencyColor = (urgency: Order['urgency']) => {
    const colors = {
      low: 'text-green-600',
      medium: 'text-yellow-600',
      high: 'text-orange-600',
      urgent: 'text-red-600',
    };
    return colors[urgency] || colors.medium;
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-admin-primary"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
        <div className="flex items-center">
          <i className="fas fa-exclamation-circle mr-2"></i>
          <span>{error}</span>
          <button
            onClick={loadData}
            className="ml-auto text-red-600 hover:text-red-800"
          >
            重试
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <div className="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
          <div className="flex items-center">
            <div className="p-3 rounded-full bg-blue-100">
              <i className="fas fa-clipboard-list text-blue-600 text-xl"></i>
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-500">总工单数</p>
              <p className="text-2xl font-bold text-gray-900">{statistics?.totalOrders || 0}</p>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
          <div className="flex items-center">
            <div className="p-3 rounded-full bg-yellow-100">
              <i className="fas fa-clock text-yellow-600 text-xl"></i>
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-500">待处理</p>
              <p className="text-2xl font-bold text-gray-900">{statistics?.statusDistribution?.waiting || 0}</p>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
          <div className="flex items-center">
            <div className="p-3 rounded-full bg-indigo-100">
              <i className="fas fa-cog text-indigo-600 text-xl"></i>
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-500">处理中</p>
              <p className="text-2xl font-bold text-gray-900">{statistics?.statusDistribution?.processing || 0}</p>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
          <div className="flex items-center">
            <div className="p-3 rounded-full bg-green-100">
              <i className="fas fa-check-circle text-green-600 text-xl"></i>
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-500">已完成</p>
              <p className="text-2xl font-bold text-gray-900">{statistics?.statusDistribution?.completed || 0}</p>
            </div>
          </div>
        </div>
      </div>

      {/* 更多统计信息 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
          <h3 className="text-lg font-medium text-gray-900 mb-4">服务质量</h3>
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-500">平均评分</span>
              <div className="flex items-center">
                <span className="text-lg font-semibold text-gray-900">
                  {statistics?.averageRating?.toFixed(1) || '0.0'}
                </span>
                <i className="fas fa-star text-yellow-400 ml-1"></i>
              </div>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-500">完成率</span>
              <span className="text-lg font-semibold text-gray-900">
                {statistics?.completionRate?.toFixed(1) || '0.0'}%
              </span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-500">今日新增</span>
              <span className="text-lg font-semibold text-gray-900">
                {statistics?.totalOrders || 0}
              </span>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
          <h3 className="text-lg font-medium text-gray-900 mb-4">人员统计</h3>
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-500">总用户数</span>
              <span className="text-lg font-semibold text-gray-900">
                {statistics?.totalUsers || 0}
              </span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-500">维修员数</span>
              <span className="text-lg font-semibold text-gray-900">
                {statistics?.totalMaintainers || 0}
              </span>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
          <h3 className="text-lg font-medium text-gray-900 mb-4">快捷操作</h3>
          <div className="space-y-3">
            <Link
              to="/orders?status=pending"
              className="block w-full text-center py-2 px-4 bg-yellow-100 text-yellow-800 rounded-lg hover:bg-yellow-200 transition-colors duration-200"
            >
              处理待办工单
            </Link>
            <Link
              to="/orders"
              className="block w-full text-center py-2 px-4 bg-blue-100 text-blue-800 rounded-lg hover:bg-blue-200 transition-colors duration-200"
            >
              查看所有工单
            </Link>
            <Link
              to="/maintainers"
              className="block w-full text-center py-2 px-4 bg-green-100 text-green-800 rounded-lg hover:bg-green-200 transition-colors duration-200"
            >
              管理维修员
            </Link>
          </div>
        </div>
      </div>

      {/* 最近工单 */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200">
        <div className="px-6 py-4 border-b border-gray-200">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-medium text-gray-900">最近工单</h3>
            <Link
              to="/orders"
              className="text-admin-primary hover:text-blue-600 text-sm font-medium"
            >
              查看全部 →
            </Link>
          </div>
        </div>
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  工单号
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  标题
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  状态
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  紧急程度
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  创建时间
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {recentOrders && recentOrders.length > 0 ? recentOrders.map((order) => (
                <tr key={order._id} className="hover:bg-gray-50">
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    {order.orderNumber}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {order.title}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full badge ${getStatusColor(order.status)}`}>
                      {getStatusText(order.status)}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`text-sm font-medium ${getUrgencyColor(order.urgency)}`}>
                      {order.urgency === 'urgent' && <i className="fas fa-exclamation-triangle mr-1"></i>}
                      {order.urgency === 'high' ? '高' : order.urgency === 'medium' ? '中' : order.urgency === 'urgent' ? '紧急' : '低'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {new Date(order.createdAt).toLocaleDateString()}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    <Link
                      to={`/orders/${order._id}`}
                      className="text-admin-primary hover:text-blue-600 font-medium"
                    >
                      查看详情
                    </Link>
                  </td>
                </tr>
              )) : (
                <tr>
                  <td colSpan={6} className="px-6 py-8 text-center text-gray-500">
                    {loading ? '加载中...' : '暂无工单数据'}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
          {!loading && recentOrders && recentOrders.length === 0 && (
            <div className="text-center py-8 text-gray-500">
              暂无工单数据
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Dashboard;